<template lang="pug">
el-dialog(
  :visible.sync="show"
  width="1328px"
  @open="beforeOpen"
  @opened="opened"
  :before-close="handleClose"
  custom-class="dialog-border"
  :close-on-click-modal="false"
)
  .modal-title(slot="title") 发布信息
  .modal-content
    el-form(:model="form" label-width="100px")
      el-form-item(label="选择栏目：" required)
        el-select(placeholder="请选择栏目" v-model="form.type")
          el-option(v-for="item, index in columns", :key="index", :label="item.label", :value="item.value")
      el-form-item(label="信息标题：" required)
        el-input(placeholder="请输入信息标题" maxlength="30" show-word-limit v-model="form.title")
      el-form-item(label="接收人员：" required)
        el-radio-group(v-model="form.type")
          el-radio(label="1" disabled) 全体用户
          el-radio(label="2" disabled) 设计师用户
          el-radio(label="3" disabled) 供应商用户
      el-form-item.form-item-quill(label="信息详情：" required)
        .form-item-quill-bd
          quill-editor(
            ref="myQuillEditor"
            v-model="form.detail"
            :options="editorOption" 
          )
      el-form-item(label="文件上传：")
        .form-item-upload
          el-upload(
            action="#"
            :multiple="false"
            ref="styleUpload"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleStyleChange"
          )
            el-button(size="small" type="primary") 点击上传
            .upload-tip(slot="tip") 支持格式.rar .zip .doc .docx .pdf，单个文件不能超过20M
  .edit-hidden-upload(v-show="false")
    el-upload(
      action="#"
      class="upload-demo"
      :multiple="true"
      accept="image/png, image/jpeg, image/jpg"
      ref="hiddenUpload"
      :show-file-list="false"
      :auto-upload="false"
      :on-change="handleQuillChange"
    )
      el-button(size="small" name="primary" slot="trigger") 上传图片
  .modal-footer(slot="footer")
    el-button(size="small" @click="handleClose") 取消
    el-button(size="small" type="primary" @click="save") 确定
</template>

<script>
import Quill from 'quill'
import { FileUpload, releaseMessage } from 'api'
export default {
  name: 'editNoticeDialog',
  props: {
    show: Boolean
  },
  data () {
    return {
      editorOption: {
        placeholder: '请输入自定义内容',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ script: 'sub' }, { script: 'super' }],
            [{ indent: '-1' }, { indent: '+1' }],
            [{ direction: 'rtl' }],
            [{ size: ['small', false, 'large', 'huge' ] }],
            [{ header: [1, 2, 3, 4, false] }],
            [{ color: [] }, { background: [] }],
            [{ font: [] }],
            [{ align: [] }],
            ['image'],
            ['clear']
          ]
        }
      },
      columns: [
        { label: '系统分享', value: '1' },
        { label: '设计师分享', value: '2' },
        { label: '供应商分享', value: '3' }
      ],
      form: {
        type: '',
        title: '',
        detail: '',
        fileList: []
      },
      fileList: []
    }
  },
  methods: {
    imgHandler(state) {
      this.addRange = this.$refs.myQuillEditor.quill.getSelection()
      if (state) {
        this.$refs.hiddenUpload.$children[0].$refs.input.click()
      }
      this.uploadType = 'image'
    },
    // 富文本图片上传
    async handleQuillChange (file, fileList) {
      try {
        let host = window.location.hostname === '123.58.39.242' || window.location.hostname === '192.168.2.71' ? 'https://ja-material-formal.oss-cn-shenzhen.aliyuncs.com' : 'https://ja-material-test.oss-cn-shenzhen.aliyuncs.com'
        let fileObj = await this.fileUpload(file.raw)
        this.$refs.myQuillEditor.quill.insertEmbed(this.addRange !== null ? this.addRange.index : 0, this.uploadType, `${host}${fileObj.fileUrl}`, Quill.sources.USER)
        this.$refs.hiddenUpload.clearFiles()
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async fileUpload (raw) {
      return new Promise(async (resolve, reject) => {
        try {
          let formData = new FormData()
          formData.append('Filedata', raw)
          formData.append("applicationId", 4)
          const { ResultSet } = await this.$axios.post(FileUpload, { formData: formData, isUpload: true }, { headers:{ "Content-Type": "multipart/form-data" } })
          resolve({ ...ResultSet.Result[0] })
        } catch (err) {
          console.log(err)
          reject(err)
        }
      })
    },
    async save () {
      try {
        if (!this.form.type) {
          this.$message.error('请先选择消息栏目！')
          return
        }
        if (!this.form.title) {
          this.$message.error('请先输入消息标题！')
          return
        }
        if (!this.form.detail) {
          this.$message.error('请先输入信息详情！')
          return
        }
        this.loading = this.$loading({
          lock: true,
          text: '保存中....',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        if (this.fileList.length) {
          let fileIds = await Promise.all(this.fileList.map(async (item) => {
            try {
              const file = await this.fileUpload(item.raw)
              return { fileId: file.fileId }
            } catch (err) {
              console.error('error: ' + JSON.stringify(err))
            }
          }))
          fileIds.forEach(item => {
            this.form.fileList.push(item.fileId)
          })
        }
        await this.$axios.post(releaseMessage, { ...this.form })
        this.$emit('confirm')
        setTimeout(() => {
          this.loading.close()
        }, 1000)
      } catch (err) {
        setTimeout(() => {
          this.loading.close()
        }, 1000)
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    beforeOpen () {
      this.form = {
        type: '',
        title: '',
        detail: '',
        fileList: []
      }
    },
    opened () {
      this.$refs.myQuillEditor.quill.enable(false)
      this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)
      setTimeout(() => {
        this.$refs.myQuillEditor.quill.enable(true)
      }, 1000)
    },
    handleClose () {
      this.$emit('close')
    },
    handleStyleChange(file, fileList) {
      this.fileList = fileList
    }
  }
} 
</script>

<style lang="scss" scoped>
.modal-content {
  max-height: 500px;
  overflow-y: auto;
  .form-item-quill {
    &/deep/.el-form-item__content {
      line-height: 1;
    }
  }
}
.form-item-quill-bd {
  min-height: 166px;
  & /deep/ .ql-container {
    min-height: 100px;
    background: #fff;
  }
}
.form-item-upload {
  width: 600px;
}
</style>
